package com.comp3111.happymeal;

import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.configuration.Configuration;
import com.configuration.Owner;
import com.controller.MealCommentFetch;
import com.controller.UserFetch;
import com.object.MealComment;
import com.object.User;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.ThumbnailUtils;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.SimpleAdapter.ViewBinder;

public class UserProfileFollowingListActivity extends NavigationDrawerActivity {

	private ListView listView;
    private SimpleAdapter adapter;
    private List<Integer> userIdList;
    
    //Show picture in listview
    String userProfilePictureDrawableURL;
    Drawable userProfilePicture;
    
    int user_id;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.page_using_listview_only);
        createDrawer();
        
        Bundle extras = getIntent().getExtras();
		user_id  = Integer.parseInt(extras.getString("USERID"));
        
        listView = (ListView)findViewById(R.id.page_using_listview_only_listview);
        adapter = new SimpleAdapter(this, getFollowing(), R.layout.following_list,
				new String[]{"user_pic","user_name"},
				new int[]{R.id.user_pic, R.id.user_name});
        listView.setAdapter(adapter);
        
        adapter.setViewBinder(new ViewBinder(){
        	public boolean setViewValue(View view,Object data,String textRepresentation){
				if(view instanceof ImageView && data instanceof Drawable){
					ImageView iv=(ImageView)view;
					iv.setImageDrawable((Drawable)data);
					return true;
				}
				else return false;
			}
        });
        
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
            	
            	int userId = userIdList.get(position);
                
                //Jump to FoodFoodPageActivity
                Intent intentPass = new Intent(UserProfileFollowingListActivity.this, UserProfileActivity.class);
				
				//Pass pass intent								
				intentPass.putExtra("USERID",Integer.toString(userId).trim());
					
				//Go to next page
				startActivity(intentPass);

            }
        });  
        
        /*
        listView.setOnTouchListener(new View.OnTouchListener() {
            public boolean onTouch(View v, MotionEvent event) {
            	
            	if(event.getAction()!= MotionEvent.ACTION_UP){
            		return false;
            	}
            	
            	int itemNum = listView.getCount();
                
            	
            	
                if(itemNum == 0){
                	return false;
                }
                
                //Transform the y to position
            	float y = (int) event.getY();
                float itemHeight = listView.getHeight()/itemNum;
                int position = -1;
                
                for(int i=0;i<itemNum;i++){
                	float lower = i*itemHeight;
                	float upper = lower + itemHeight;
                	if(y>lower && y<upper){
                		position = i;
                	}
                }
                
                if(position>itemNum-1 || position<0){
                	return false;
                }
                
            	int userId = userIdList.get(position);
                
                //Jump to FoodFoodPageActivity
                Intent intentPass = new Intent(UserProfileFollowingListActivity.this, UserProfileActivity.class);
				
				//Pass pass intent								
				intentPass.putExtra("USERID",Integer.toString(userId).trim());
					
				//Go to next page
				startActivity(intentPass);
                // Disallow the touch request for parent scroll on touch of
                // child view
                v.getParent().requestDisallowInterceptTouchEvent(true);
                return false;
            }
        });
        */
    }
    
    private List<Map<String, Object>> getFollowing() {

    	List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
    		
    	userIdList = new ArrayList<Integer>();
    	
    	UserFetch userFetch = new UserFetch();
    	List<User> userList = userFetch.fetchUserFollowingById(user_id);
    		
    	
    	if(userList != null){
    		for(User user:userList){
    	    	// Display all following
    						
    			//drawableURL = Configuration.baseURL + restaurant.getProfilePicture();
	    		Map<String, Object> map = new HashMap<String, Object>();
				
	    		if(user.getProfilePicture()!=null){
					
					userProfilePictureDrawableURL = Configuration.baseURL + user.getProfilePicture();
					
					//Start a new thread and use POST method to send telephone and passcode to authURL
			        //Start a new thread to attempt Login (requirement when connecting online)
					Thread attemptThread = new Thread(new Runnable(){  
						public void run(){  
							
							userProfilePicture = loadImageFromURL(userProfilePictureDrawableURL);		
						}
					});  
					attemptThread.start();
					
					while(attemptThread.isAlive()){
						//Wait for server response
					}
				}
				
				map.put("user_pic",userProfilePicture);
	    		//map.put("user_pic", R.drawable.profile_pic_2);
	    		map.put("user_name", user.getName());
	    		map.put("unfollow_btn", "UNFOLLOW");
	    		
	    		list.add(map);
	    		
	    		//List containing user id in order
    			userIdList.add(user.getId());
    		}

    	}
		return list;
	}
    
    private Drawable loadImageFromURL(String url){
        try{
        	InputStream is = (InputStream) new URL(url).getContent();
            Bitmap tmp = ThumbnailUtils.extractThumbnail(BitmapFactory.decodeStream(is),Configuration.THUMBSIZE,Configuration.THUMBSIZE);
            return new BitmapDrawable(getResources(), tmp);
            /*
            InputStream is = (InputStream) new URL(url).getContent();
            Drawable draw = Drawable.createFromStream(is, "src");
            return draw;*/
        }catch (Exception e) {
            //TODO handle error
            Log.i("loadingImg", e.toString());
            return null;
        }
    }
}